# WS server example that synchronizes state across clients
import asyncio
import logging
import time

import websockets
from . import WD_Control

logging.basicConfig()

STATE = {"value": 0}
USERS = set()
status = False


async def notify_all_user(message):
    if USERS:
        await asyncio.wait([user.send(message) for user in USERS])


async def register(websocket):
    USERS.add(websocket)


async def unregister(websocket):
    USERS.remove(websocket)


async def counter(websocket, path):
    await register(websocket)
    try:
        await websocket.send("Hello, WD_Chao Server")
        async for message in websocket:
            await handler_manager(message)
    finally:
        await unregister(websocket)


# 处理收到的消息
async def handler_manager(message):
    WD_Control.Data_Pack(message)


async def send_car_data():
    if USERS:
        postback = WD_Control.data_postback()
        await notify_all_user(postback)


async def send_data_thread():
    if status:
        return
    while True:
        time.sleep(1)
        await  send_car_data()


WD_Control.start_server()
print("设备初始化启动成功")

start_server = websockets.serve(counter, "0.0.0.0", 9900)
asyncio.get_event_loop().run_until_complete(start_server)
print("Websocket服务已启动")
asyncio.get_event_loop().run_forever()
